﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Commons.Web
{
    /// <summary>
    /// 返回jsonp上下文
    /// </summary>
    public class JsonpResult : JsonResult
    {
        const string CALLBACKNAME = "callback";
        /// <summary>
        /// 复写渲染视图方法
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("当前请求上下文出错");
            }
            if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet)
                && String.Equals(context.HttpContext.Request.HttpMethod, "GET"))
            {
                throw new InvalidOperationException("Jsonp只能是ＧＥＴ请求");
            }
            var response = context.HttpContext.Response;
            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }
            if (Data != null)
            {
                String buffer;
                var request = context.HttpContext.Request;
                var serializer = new JavaScriptSerializer();
                if (request[CALLBACKNAME] != null)
                    buffer = String.Format("{0}({1})", request[CALLBACKNAME], serializer.Serialize(Data));
                else
                    buffer = serializer.Serialize(Data);
                response.Write(buffer);
            }
        }
    }



}
